<template>
  <a-modal
    :title="this.BaseTool.String.isBlank(userId)?'添加用户':'编辑用户'"
    :width="640"
    :visible="visible"
    :confirmLoading="confirmLoading"
    @cancel="handleCancel"
  >
    <a-form :form="form">
      <a-form-item v-show="false" >
        <a-input v-decorator="['userId']" type="hidden"/>
      </a-form-item>
      <a-form-item
        label="用户名"
        :labelCol="labelCol"
        :wrapperCol="wrapperCol"
      >
        <a-input v-decorator="['username', {rules: [{required: true, message: '请输入用户名'},{ validator: this.handleUsernameCheck }], validateTrigger: ['blur']}]"/>
      </a-form-item>
      <a-form-item
        label="姓名"
        :labelCol="labelCol"
        :wrapperCol="wrapperCol"
      >
        <a-input v-decorator="['realName', {rules: [{required: true, message: '请输入姓名'}]}]" />
      </a-form-item>

      <a-form-item
        label="头像"
        :labelCol="labelCol"
        :wrapperCol="wrapperCol"
        v-show="false"
      >
        <a-input v-decorator="['avatar', {initialValue: '/logo_custom.png'}]" />
      </a-form-item>

      <a-form-item
        label="手机号"
        :labelCol="labelCol"
        :wrapperCol="wrapperCol"
      >
        <a-input v-decorator="['phone']"/>
      </a-form-item>
      <a-form-item
        label="邮箱"
        :labelCol="labelCol"
        :wrapperCol="wrapperCol"
      >
        <a-input v-decorator="['email']"/>
      </a-form-item>
<!--      <a-form-item
        label="身份"
        :labelCol="labelCol"
        :wrapperCol="wrapperCol"
      >
        <a-select
          @change="changeIdentityType"
          :show-search="true"
          :filter-option="BaseTool.ANTD.selectFilterOption"
          v-decorator="['identityType']"
          placeholder="请选择">
          <a-select-option
            v-for="(label,value) in identityTypeMap"
            :key="value"
            :label="label"
            :value="parseInt(value)">{{ label }}
          </a-select-option>
        </a-select>
      </a-form-item>-->
<!--      <a-form-item
        label="职务"
        :labelCol="labelCol"
        :wrapperCol="wrapperCol"
      >
        <a-select
          :show-search="true"
          :filter-option="BaseTool.ANTD.selectFilterOption"
          v-decorator="['jobType']"
          placeholder="请选择">
          <a-select-option
            v-for="(label,value) in jobTypeMap"
            :key="value"
            :label="label"
            :value="parseInt(value)">{{ label }}
          </a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item
        label="国家"
        :labelCol="labelCol"
        :wrapperCol="wrapperCol"
      >
        <a-select
          :show-search="true"
          :filter-option="BaseTool.ANTD.selectFilterOption"
          v-decorator="['country']"
          placeholder="请选择">
          <a-select-option
            v-for="(label,value) in countryMap"
            :key="value"
            :label="label"
            :value="parseInt(value)">{{ label }}
          </a-select-option>
        </a-select>
      </a-form-item>

      <a-form-item
        label="币种"
        :labelCol="labelCol"
        :wrapperCol="wrapperCol"
      >
        <a-select v-decorator="['moneyTypes']" placeholder="请选择" mode="multiple">
          <a-select-option
            v-for="(label,value) in moneyTypeMap"
            :key="value"
            :label="label"
            :value="parseInt(value)">{{ label }}
          </a-select-option>
        </a-select>
      </a-form-item>

      <a-form-item
        label="是否自动审批"
        :labelCol="labelCol"
        :wrapperCol="wrapperCol"
      >
        <a-checkbox
          v-decorator="[ 'enquiryAutoAudit', { valuePropName: 'checked',initialValue: true, }]" >
        </a-checkbox>
      </a-form-item>-->

      <!--      <a-form-item-->
      <!--        label="汇率"-->
      <!--        v-if="hasExchangeRate"-->
      <!--        :labelCol="labelCol"-->
      <!--        :wrapperCol="wrapperCol"-->
      <!--      >-->
      <!--        <a-input-number-->
      <!--          style="width: 100%"-->
      <!--          :min="0"-->
      <!--          :step="0.01"-->
      <!--          :formatter="BaseTool.Amount.formatter"-->
      <!--          :parser="BaseTool.Amount.parser"-->
      <!--          v-decorator="['exchangeRate', {rules: [{required: true, message: '汇率不能为空'}]}]"/>-->
      <!--      </a-form-item>-->

<!--      <a-form-item
        label="地址"
        :labelCol="labelCol"
        :wrapperCol="wrapperCol"
      >
        <a-input v-decorator="['addressDetail']"/>
      </a-form-item>-->
      <a-form-item
        label="角色"
        :labelCol="labelCol"
        :wrapperCol="wrapperCol"
      >
        <a-select
          :show-search="true"
          :filter-option="BaseTool.ANTD.selectFilterOption"
          v-decorator="['roleIds', {rules: [{required: true, message: '请选择角色'}]}]"
          mode="multiple">
          <a-select-option
            v-for="item in roleList"
            :key="item.roleId"
            :label="item.roleName"
            :value="item.roleId">{{ item.roleName }}</a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item
        label="是否超级管理员"
        :labelCol="{lg: {span: 7}, sm: {span: 7}}"
        :wrapperCol="{lg: {span: 10}, sm: {span: 17} }">
        <a-switch :checked="superAdmin" @change="handleSuperAdminChange" />
      </a-form-item>
      <a-form-item
        label="选择部门"
        :labelCol="labelCol"
        :wrapperCol="wrapperCol"
        :required="true"
      >
        <a-tree
          checkable
          @expand="onExpand"
          :expandedKeys="expandedKeys"
          :autoExpandParent="autoExpandParent"
          v-model="checkedKeys"
          @check="onCheck"
          @select="onSelect"
          :check-strictly="true"
          :selectedKeys="selectedKeys"
          :treeData="treeData"
        />
      </a-form-item>
    </a-form>
    <template slot="footer">
      <a-button :loading="confirmLoading" type="primary" @click="save()">保存</a-button>
    </template>
  </a-modal>
</template>

<script>
import pick from 'lodash.pick'
import { addUser, updateUser, queryUser } from '@/api/upms/user'

export default {
  name: 'UserBase',
  data () {
    return {
      labelCol: {
        xs: { span: 24 },
        sm: { span: 7 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 13 }
      },
      visible: false,
      superAdmin: false,
      confirmLoading: false,
      currentStep: 0,
      mdl: {},
      hasCountry: false,
      hasAddress: false,
      hasMoneyType: false,
      hasExchangeRate: false,
      hasCountryIdentityTypes: [],
      userId: null,
      identityTypeMap: {},
      countryMap: {},
      moneyTypeMap: {},
      jobTypeMap: {},
      checkedKeys: [],
      autoExpandParent: true,
      expandedKeys: [],
      selectedKeys: [],
      halfCheckedKeys: [],

      form: this.$form.createForm(this)
    }
  },
  props: {
    roleList: {
      type: Array,
      default: () => ({})
    },
    treeData: {
      type: Array,
      default: () => ({})
    }
  },
  created () {
    // 下拉框map
    this.identityTypeMap = this.DictCache.getLabelByValueMapByType(this.DictCache.TYPE.SYS_USER_IDENTITY_TYPE)
    this.countryMap = this.DictCache.getLabelByValueMapByType(this.DictCache.TYPE.SYS_USER_COUNTRY)
    this.moneyTypeMap = this.DictCache.getLabelByValueMapByType(this.DictCache.TYPE.MONEY_TYPE)
    this.jobTypeMap = this.DictCache.getLabelByValueMapByType(this.DictCache.TYPE.SYS_USER_JOB_TYPE)
    this.hasCountryIdentityTypes = [this.DictCache.VALUE.SYS_USER_IDENTITY_TYPE.CGY,
      this.DictCache.VALUE.SYS_USER_IDENTITY_TYPE.FHY,
      this.DictCache.VALUE.SYS_USER_IDENTITY_TYPE.SHY]
  },
  methods: {
    base (record) {
      this.userId = null
      this.form.resetFields()
      this.visible = true
      this.hasCountry = false
      this.hasAddress = false
      this.hasMoneyType = false
      this.hasExchangeRate = false
      // 如果是空标识添加
      if (this.BaseTool.Object.isBlank(record)) {
        return
      }
      if (this.BaseTool.Object.isBlank(record)) {
        return
      }
      const { form: { setFieldsValue } } = this
      this.hasCountry = this.hasCountryIdentityTypes.includes(record.identityType)
      this.hasAddress = this.hasCountryIdentityTypes.includes(record.identityType)
      this.hasMoneyType = this.hasCountryIdentityTypes.includes(record.identityType)
      this.hasExchangeRate = this.hasCountryIdentityTypes.includes(record.identityType)
      this.$nextTick(() => {
        this.userId = record.userId
        this.checkedKeys = record.deptIds
        this.expandedKeys = record.deptIds
        setFieldsValue(pick(record, ['userId', 'username','email', 'enquiryAutoAudit', 'realName', 'phone', 'roleIds', 'identityType', 'jobType']))
        if (this.hasCountry) {
          setFieldsValue(pick(record, ['country']))
        }
        if (this.hasAddress) {
          setFieldsValue(pick(record, ['addressDetail']))
        }
        if (this.hasMoneyType) {
          setFieldsValue(pick(record, ['moneyTypes']))
        }
        if (this.hasExchangeRate) {
          setFieldsValue(pick(record, ['exchangeRate']))
        }
        this.superAdmin = (record.superAdmin === 1)
      })
    },
    handleUsernameCheck (rule, value, callback) {
      if (!value) {
        callback()
        return
      }
      queryUser({ username: value }).then(res => {
        if (res.data && res.data.length > 0) {
          const id = res.data[0].userId
          if (this.userId == null || id !== this.userId) {
            callback(new Error('用户名已存在!'))
          } else {
            callback()
          }
        } else {
          callback()
        }
      })
    },
    changeIdentityType (val) {
      this.hasCountry = this.hasCountryIdentityTypes.includes(val)
      this.hasAddress = this.hasCountryIdentityTypes.includes(val)
      this.hasMoneyType = this.hasCountryIdentityTypes.includes(val)
      this.hasExchangeRate = this.hasCountryIdentityTypes.includes(val)
    },
    handlePhoneCheck (rule, value, callback) {
      if (value && value.length === 11) {
        queryUser({ username: value }).then(res => {
          if (res.data && res.data.length > 0) {
            const id = res.data[0].userId
            if (this.userId == null || id !== this.userId) {
              callback(new Error('手机号已存在!'))
            } else {
              callback()
            }
          } else {
            callback()
          }
        })
      } else {
        callback()
      }
    },
    save () {
      const { form: { validateFields }, $message } = this
      this.confirmLoading = true
      validateFields({ force: true }, (errors, values) => {
        if (!errors) {
          if (this.checkedKeys.length === 0) {
            $message.error('请勾选部门')
            this.confirmLoading = false
            return
          }
          if (this.checkedKeys.length > 1) {
            $message.error('只能选择一个部门')
            this.confirmLoading = false
            return
          }
          values = {
            ...values,
            deptIds: [...this.checkedKeys],
            superAdmin: this.superAdmin ? 1 : 0
          }
          if (this.BaseTool.String.isBlank(this.userId)) {
            addUser(values)
              .then(() => {
                setTimeout(() => {
                  this.visible = false
                  this.confirmLoading = false
                  this.$emit('ok', values)
                }, 1500)
              }).catch(() => {
                this.confirmLoading = false
              })
          } else {
            updateUser(values)
              .then(() => {
                setTimeout(() => {
                  this.visible = false
                  this.confirmLoading = false
                  this.$emit('ok', values)
                }, 1500)
              }).catch(() => {
                this.confirmLoading = false
              })
          }
        } else {
          this.confirmLoading = false
        }
      })
    },
    handleCancel () {
      this.visible = false
      this.form = this.$form.createForm(this)
      this.superAdmin = false
      this.userId = null
      this.checkedKeys = []
      this.form.resetFields()
    },
    handleSuperAdminChange () {
      this.superAdmin = !this.superAdmin
    },
    onExpand (expandedKeys) {
      this.expandedKeys = expandedKeys
      this.autoExpandParent = false
    },
    onCheck (checkedItem, info) {
      if (checkedItem.checked.length > 0) {
        this.checkedKeys = [checkedItem.checked[checkedItem.checked.length - 1]]
        this.selectedKeys = this.checkedKeys
      } else {
        this.checkedKeys = []
        this.selectedKeys = this.checkedKeys
      }
      console.log(1111, this.checkedKeys, checkedItem, info)
    },
    onSelect (selectedKeys, info) {
      console.log('onSelect', selectedKeys, info)
      this.selectedKeys = selectedKeys
      this.checkedKeys = selectedKeys
      console.log(1111333, this.checkedKeys)
    }
  }
}
</script>
